import { Button, Empty, Grid, Message, Progress, Table } from '@arco-design/web-react';
import { useEffect, useRef, useState } from 'react';
import main from '../main';
import { apiGetTaskMqImportList,apiExportTaskMqImportDetail, apiGetTaskMqImportDetailList  } from '../api';
import { TaskMqImport } from '../types';
import { TaskMqImportDetail } from '../types';
import { delay } from '../utils/utils';
import DetailModal from './detailModal';
import LoadingMask from './loadingMask';
import { IconExport } from '@arco-design/web-react/icon';
import ExportFileDialog from './exportFileDialog';

interface Props {
  title: string;
  taskKey?: string;
  params?: any;
  onCancel: () => void;
  // exportFn: (params: any) => Promise<AxiosResponse<any, any>>;
}
export default function ImportFileDialog({ title, taskKey, params, onCancel }: Props) {
  // 显示详情列表弹窗
  const [showDetailList, setShowDetailList] = useState<TaskMqImport>();
  const [list, setList] = useState<TaskMqImport[]>([]);
  const [fetching, setFetching] = useState(false);
  const [loaded, setLoaded] = useState(false);
  const [error, setError] = useState('');
  const [total, setTotal] = useState(1);
  const [pageNum, setPageNum] = useState(1);
  const [pageSize, setPageSize] = useState(main.defaultPageSize);

  const unmontRef = useRef(false);
  const pageRef = useRef({ pageNum, pageSize });

  useEffect(() => {
    return () => {
      unmontRef.current = true;
    };
  }, []); //eslint-disable-line

  useEffect(() => {
    loadProgress();
  }, [pageNum, pageSize]); // eslint-disable-line

  async function loadProgress() {
    if (pageNum !== pageRef.current.pageNum || pageSize !== pageRef.current.pageSize) {
      return;
    }
    setFetching(true);
    try {
      let res = await apiGetTaskMqImportList(
        pageNum,
        pageSize,
        Object.assign({ exportName: taskKey, isAsc: 'desc', orderByColumn: 'id' }, params)
      );
      let data = res.data;
      if (!loaded) {
        setLoaded(true);
      }
      if (data.code === 200) {
        setFetching(false);
        setLoaded(true);
        setTotal(data.total);
        setList(data.rows ?? []);

        let some = data.rows.some(
          (item: TaskMqImport) => item.status !== 'success' && item.status !== 'failure' && item.status !== 'error'
        );
        if (some) {
          await delay(1000);
          if (!unmontRef.current) {
            loadProgress();
          }
        }
      } else {
        setError(data.msg ?? '加载失败');
        Message.warning(data.msg ?? '加载失败');
        setList([]);
      }
    } catch (e: any) {
      setError(e.messag ?? '加载失败');
      Message.warning(e.messag ?? '加载失败');
    }
  }

  /**
   * 分页器 切换分页和条数
   * @param page 当前页数
   * @param size 每页条数
   */
  function handlePageAndSizeChange(page: number, size: number) {
    if (page === pageNum && size === pageSize) return;

    Message.info('正在加载...');
    setPageSize(size);
    setPageNum(page);
    pageRef.current.pageNum = page;
    pageRef.current.pageSize = size;
  }

  let dataSource = (list || []).map((item) => Object.assign({}, item, { key: item.id }));

  // 定义类型表格内的列
  const dataColumns = [
    {
      title: '任务名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '进度',
      dataIndex: 'percentage',
      key: 'percentage',
      render: (v: number) => (
        <div className="w-200">
          <Progress percent={v} />
        </div>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (v: string) =>
        v === 'waiting' ? '排队中' : v === 'processing' ? '处理中' : v === 'success' ? '成功' : '异常',
    },
    {
      title: '状态提示',
      dataIndex: 'statusRemark',
      key: 'statusRemark',
      render: (v: string) => <div className="maxw-200">{v}</div>,
    },
    {
      title: '操作人',
      dataIndex: 'deptUserName',
      key: 'deptUserName',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
    },
    {
      title: '详情',
      dataIndex: 'detailList',
      key: 'detailList',
      render: (v: string, record: TaskMqImport) => (
        <div className="text-primary-color cursor-pointer" onClick={() => setShowDetailList(record)}>
          查看详情
        </div>
      ),
    },
  ];
  return (
    <DetailModal
      show
      title={title}
      cancelBtnShow={false}
      onConfirm={onCancel}
      onCancel={onCancel}
      className="w-1000"
      contentClassName="h-500"
    >
      <Table
        className="bw-100"
        data={dataSource}
        columns={dataColumns}
        loading={!list || (fetching && !loaded)}
        noDataElement={<Empty description={error ?? '暂无数据'} />}
        pagination={{
          className: 'pagination-block',
          total: total || 1,
          current: pageNum,
          pageSize: pageSize,
          showJumper: true,
          sizeCanChange: true,
          sizeOptions: main.defaultPageSizeOptions,
          showTotal: (total) => `共${total}条`,
          size: 'small',
          onChange: handlePageAndSizeChange,
        }}
      />
      {showDetailList && (
        <ImportFileDetailListDialog
          parentId={showDetailList.id!}
          name={showDetailList.name!}
          onCancel={() => setShowDetailList(undefined)}
        />
      )}
    </DetailModal>
  );
}

interface DetailListDialogProps {
  parentId: number;
  name: string;
  onCancel: () => void;
}
function ImportFileDetailListDialog({ parentId, name, onCancel }: DetailListDialogProps) {
  let [list, setList] = useState<TaskMqImportDetail[]>([]);
  const [fetching, setFetching] = useState(false);
  const [loaded, setLoaded] = useState(false);
  const [error, setError] = useState('');
  const [exportDialogShow, setExportDialogShow] = useState(0);

  useEffect(() => {
    setFetching(true);
    loadList();
  }, []); //eslint-disable-line

  async function loadList() {
    LoadingMask.show('正在加载...');
    try {
      let res = await apiGetTaskMqImportDetailList(1, 1000, { parentId });
      let data = res.data;
      setLoaded(true);
      setFetching(false);
      if (data.code === 200) {
        setList(data.rows ?? []);
      } else {
        setError(data.msg ?? '加载失败');
        Message.warning(data.msg ?? '加载失败');
      }
    } catch (e: any) {
      setError(e.message ?? '加载失败');
      Message.error(e.message ?? '加载失败');
    } finally {
      LoadingMask.hide();
    }
  }

  let dataSource = (list || []).map((item) => Object.assign({}, item, { key: item.id }));

  // 定义类型表格内的列
  const dataColumns = [
    {
      title: '任务名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '进度',
      dataIndex: 'percentage',
      key: 'percentage',
      render: (v: number) => (
        <div className="w-200">
          <Progress percent={v} />
        </div>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (v: string) =>
        v === 'waiting' ? '排队中' : v === 'processing' ? '处理中' : v === 'success' ? '成功' : '异常',
    },
    {
      title: '状态提示',
      dataIndex: 'statusRemark',
      key: 'statusRemark',
      render: (v: string) => <div className="maxw-200">{v}</div>,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
    },
  ];
  return (
    <DetailModal
      show
      title={`${name}详情`}
      cancelBtnShow={false}
      onConfirm={onCancel}
      onCancel={onCancel}
      className="w-1000"
      contentClassName="h-500 ac-start"
    >
      <Grid.Col span={24} className="d-flex-r jc-end pb-10">
        <Button type="primary" icon={<IconExport />} onClick={() => setExportDialogShow(1)}>
          导出
        </Button>
      </Grid.Col>
      <Table
        className="bw-100"
        data={dataSource}
        columns={dataColumns}
        pagination={false}
        loading={!list || (fetching && !loaded)}
        noDataElement={<Empty description={error ?? '暂无数据'} />}
      />
      {!!exportDialogShow && (
        <ExportFileDialog
          title="导入任务详情导出"
          taskKey="导入任务详情"
          params={{ parentId }}
          onlyDownload={exportDialogShow === 2}
          onCancel={() => setExportDialogShow(0)}
          exportFn={apiExportTaskMqImportDetail}
        />
      )}
    </DetailModal>
  );
}
